from fastapi import FastAPI
import os
from dotenv import load_dotenv
from tortoise.contrib.fastapi import register_tortoise
from application.apps.common.views import app as common_app
from . import settings
from .utils import midddleware,exceptions,redis_tools
from application.apps.users.views import app as user_app



def create_app()->FastAPI:
    """
    创建App应用对象的工厂函数
    App的初始化代码放在这里
    :return:
    """
    load_dotenv()
    app: FastAPI = FastAPI(
        title=os.environ.get('APP_NAME', 'FastAPI'),
        version=os.environ.get('APP_VERSION', '0.0.1'),
        summary=os.environ.get('APP_SUMMARY', 'FastAPI'),
        description=os.environ.get('APP_DESCRIPTION', 'FastAPI'),

        # 把全局异常函数注册到App应用对象中
        exception_handlers={
            exceptions.HTTPException:
            exceptions.global_http_exception_handler,
            exceptions.RequestValidationError:
            exceptions.global_validation_exception_handler,
        }
    )

    register_tortoise(
        app,
        config=settings.TORTOISE_ORM,
        # generate_schemas=True,
        add_exception_handlers=True,
    )
    redis_tools.register_redis(
        app,
        config=settings.REDIS
    )

    # 注册所有的分组应用对象到APP应用对象
    app.include_router(common_app,prefix='') #公共数据应用
    app.include_router(user_app, prefix='/users')  # 用户数据应用

    # 注册中间件函数
    http_middleware=app.middleware('http')
    http_middleware(midddleware.log_requests)

    return app


